import 'package:HnXG/Api.dart';
import 'package:HnXG/Request/UserLoginRequest%20.dart';
import 'package:HnXG/pages/Pages/NewWarehousePage.dart';
import 'package:HnXG/pages/tabs.dart';


import 'package:flutter/material.dart';
import 'package:HnXG/snackbar.dart';
// import 'package:signalr_netcore/signalr_client.dart';
import 'package:signalr_netcore/hub_connection_builder.dart'; // 添加这行导入



class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final _formKey = GlobalKey<FormState>();





  //初始化
  @override
  void initState()  {
    super.initState();
    // _initSignalRConnection();
  }

  Future<void> _initSignalRConnection() async {
      try {//signalr连接
final connection = HubConnectionBuilder()
    .withUrl("http://192.168.31.12:1077/chat")//http://10.10.1.19:1997/
         
    .build();   
      await connection.start();
       SuccessSnackBar.show(context, message: 'signalr: 连接成功');
      connection.on('CallByHub', (Parameters) async {
        if (Parameters != null && Parameters.length >= 3) {
     
      }});//接收消息
       print("url2:${connection.baseUrl}");
     // 删除重复的 _initSignalRConnection 方法定义
    } catch (e) {
     ErrorSnackBar.show(context, message: 'signalr: 连接失败');
       print("signalr 连接失败，具体错误信息: ${e.toString()}");
    }


  }




  @override
  Widget build(BuildContext context) {

    
    return Scaffold(
      appBar: AppBar(

    
      ),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Form(
          key: _formKey,
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center, // 新增对齐方式
              children: [
                const SizedBox(height: 20),
                // 新增图标和标题
                // 修正后的图片加载方式
                Image.asset(
                  "images/AGV-IGV.png",
                  width: 80,
                  height:80,
                ),
                const SizedBox(height: 10),
                const Text(
                  '汉拿AGV',
                  style: TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 40),
                TextFormField(
                  controller: _usernameController,
                  decoration: const InputDecoration(
                    labelText: '用户名',
                    hintText: '请输入您的账号',
                    border: OutlineInputBorder(),
                    prefixIcon: Icon(Icons.person),
                  ),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return '请输入用户名';
                    }
                    return null;
                  },
                ),
                const SizedBox(height: 20),
                TextFormField(
                  controller: _passwordController,
                  obscureText: true,
                  decoration: const InputDecoration(
                    labelText: '密码',
                    hintText: '请输入密码',
                    border: OutlineInputBorder(),
                    prefixIcon: Icon(Icons.lock),
                  ),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return '请输入密码';
                    }
                    return null;
                  },
                ),
                const SizedBox(height: 40),
                //登录按钮
                SizedBox(
                  width: double.infinity,
                  height: 50,
                  child: ElevatedButton(
                    onPressed: () async {
                      if (_formKey.currentState!.validate()) {
                        // 执行登录操作
                        final username = _usernameController.text;
                        final password = _passwordController.text;
                        // 调用登录接口
                      final response=   await  Api.loginRequest( UserLoginRequest(username: username, password: password));  
                      if(response['state']==true){
                        // 登录成功，跳转到首页或其他页面
                        SuccessSnackBar.show(context, message: '登录成功');
                         _passwordController.clear(); // 新增清空密码
                         Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context){
                          return const Tabs();
                         }));



                      }
                      else{
                        // 登录失败，显示错误信息
                         ErrorSnackBar.show(context, message: response['msg']);
                        }
                  

                      }
                    },
                    child: const Text('登 录(账号:admin 密码:abc123)',
                        style: TextStyle(fontSize: 18)),
                  ),
                ),
                const SizedBox(height: 20),  // 新增间距
                // 新增测试按钮
                SizedBox(
                  width: double.infinity,
                  height: 50,
                  child: ElevatedButton(
                    onPressed: () async {

  
                      final response = await Api.testRequest();
                      if (response['state'] == true) {
                        SuccessSnackBar.show(context, message:"网络正常:${response['dto']}");
                        
                      } else {
                        ErrorSnackBar.show(context, message: '网络异常');
                      }
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.grey[200], // 灰色背景
                      foregroundColor: Colors.black, // 黑色文字
                    ),
                    child: const Text('网络测试,切换模式Debug||Release'),
                  ),
                ),
              
              ],
            ),
          ),
        ),
      ),
      // 移除底部导航栏参数
    );
  }
}